package com.cml.batisext.core.repository.mybatis.base.sqlprovider;

import java.lang.reflect.Field;
import java.util.List;

import com.cml.batisext.core.exception.BatisExtException;
import com.cml.batisext.core.repository.mybatis.annotations.DbField;
import com.cml.batisext.core.repository.mybatis.annotations.DbTable;
import com.cml.batisext.core.repository.mybatis.base.BaseDaoSqlProvider;
import com.cml.batisext.core.repository.mybatis.base.SelectSort;

/**
 * 通用dao查询语句SQL生成器
 * 
 * 为根据主键查询实体，和根据传入实体查询实体列表的方法提供sql
 * 
 * @author lwh
 * 
 */
public class BaseDaoSelectSqlProvider extends BaseDaoSqlProvider {

	public String doBuildSql(Object param, Class<?> beanType) throws Exception {

		if(beanType == null){
			throw new BatisExtException("获取实体类型失败，请确认mybatyis拦截器已在容器中注册");
		}
		String tableName = beanType.getAnnotation(DbTable.class).table();

		String sqlField = " ";
		// 根据实体查询
		if (param instanceof Long) {
			List<Field> fields = getAllDbField(beanType);
			for (Field f : fields) {
				DbField field = f.getAnnotation(DbField.class);
				// 只对标注了为数据库字段的属性进行处理
				if (field == null) {
					continue;
				}
				sqlField += getColumnName(f, field) + ",";
			}
			return "select " + sqlField.substring(0, sqlField.length() - 1)
					+ " from " + tableName + " where id = " + param;
		} else {
			List<Field> beanFields = getAllDbField(beanType);

			String tmpColumnName = null;
			Class<?> tmpColumnType = null;
			String sqlWhere = "";
			boolean hasWhere = false;
			Object fieldValue = null;
			for (Field f : beanFields) {
				DbField field = f.getAnnotation(DbField.class);
				// 只对标注了为数据库字段的属性进行处理
				if (field == null) {
					continue;
				}

				tmpColumnName = getColumnName(f, field);
				tmpColumnType = getColumnType(f, field);

				sqlField += tmpColumnName + ",";

				fieldValue = getColumnValue(param, f, beanType);

				if (fieldValue != null) {
					hasWhere = true;
					sqlWhere += tmpColumnName + " = "
							+ setupFieldValue(tmpColumnType, fieldValue)
							+ " and ";
				}
			}
			String sql = "select "
					+ (sqlField.length() > 1 ? sqlField.substring(0,
							sqlField.length() - 1) : "");
			sql += " from " + tableName;
			if (hasWhere) {
				sql += " where " + sqlWhere.substring(0, sqlWhere.length() - 4);
			}
			
			if(param instanceof SelectSort){
				if(((SelectSort)param).orderBy() != null){
					sql += " order by " + ((SelectSort)param).orderBy();
				}
			}
			return sql;
		}
	}

}
